import 'dart:convert';
import 'dart:math';

import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/pages/expert/mine_page.dart';
import 'package:chathouse/pages/expert/wallet_page.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/public/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../constant/app_constant.dart';
import '../../model/client_search_model.dart';
import '../../model/member_info.dart';
import '../../util/base_utils.dart';
import '../../widgets/base_appbar.dart';
import '../../widgets/my_input_widget.dart';
import '../base/base.dart';

class EditExpertService extends BaseStatefulWidget {
  Map? map;

  EditExpertService(this.map, {Key? key}) : super(key: key);

  @override
  // ignore: no_logic_in_create_state
  _EditExpertServiceState createState() => _EditExpertServiceState(map);
}

class _EditExpertServiceState extends BaseStatefulWidgetState<EditExpertService>
    with NavigationHelper {
  ClientSearchModel? clientSearchModel;
  Map? map;
  MemberInfo? _memberInfo;
  List<String>? selectTypes;

  TextEditingController titleControl = TextEditingController();
  TextEditingController tagControl = TextEditingController();

  _EditExpertServiceState(this.map);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      updateState(LoadState.success);
    });

    Apis.getMembersInfo().then((value) {
      _memberInfo = MemberInfo.fromJson(value?.data);
      titleControl.text = _memberInfo?.data?.membersTitle ?? "";
      tagControl.text = _memberInfo?.data?.describeExperience ?? "";
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
      if (_memberInfo?.data?.serviceName != null) {
        selectTypes = _memberInfo?.data?.serviceName?.split(",");
      }
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
    }).onError((error, stackTrace) {});

    selectTypes = [];
    Obj.showLoading();
    Apis.getHotList().then((response) {
      Obj.dismissLoading();
      var data = response?.data;
      if (data == null) {
        return;
      }
      setState(() {
        clientSearchModel = ClientSearchModel.fromJson(data);
      });
    }).catchError((error) {
      Obj.dismissLoading();
    });
  }

  showQuoteMsg() {
    showDialog(
        context: context,
        barrierColor: Colors.black54,
        builder: (BuildContext context) {
          return Container(
            child: Center(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                width: 358.w,
                height: 370.w,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(Styles.magin_40)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("提示",
                        textAlign: TextAlign.center,
                        style: getTextStyle(29.sp,
                            fontType: FontType.BOLD,
                            color: Styles.colorHomeRight)),
                    SizedBox(
                      height: 12.w,
                    ),
                    Text("專家服務最多只能免費四項選擇.如需新添加服務需扣除額外50個代幣服務費",
                        textAlign: TextAlign.center,
                        style: getTextStyle(29.sp,
                            fontType: FontType.MID, color: Styles.c_191919)),
                    SizedBox(
                      height: 30.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.FF9800,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "了解",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 20.w),
                      ),
                    ).setOnClickListener(() {
                      Navigator.pop(context);
                      onSave(false);
                    }),
                    SizedBox(
                      height: 12.w,
                    )
                  ],
                ),
              ),
            ),
          );
          // );
        });
  }

  showMaxMsg(String serviceId) {
    showDialog(
        context: context,
        barrierColor: Colors.black54,
        builder: (BuildContext context) {
          return Container(
            // color: Colors.black26,
            child: Center(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                width: 358.w,
                height: 340.w,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(Styles.magin_40)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text("你的服務選項己超過基本的四項選擇.本次添加需扣除${_memberInfo?.money}個代幣服務費",
                        textAlign: TextAlign.center,
                        style: getTextStyle(29.sp,
                            fontType: FontType.MID, color: Styles.c_191919)),
                    SizedBox(
                      height: 44.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.FF9800,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "確認",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 20.w),
                      ),
                    ).setOnClickListener(() {
                      onSave(true);
                    }),
                    // for ref
                    // Container(
                    //     child: ImageUtils.image(
                    //         Res.service_legal_engineering))
                    //     .setOnClickListener(() {
                    //   navigateTo(const LegalEngineeringPage());
                    //   // Get.to(const LegalEngineeringPage());
                    // }, isInkWell: true),
                    SizedBox(
                      height: 12.w,
                    ),
                    Container(
                      alignment: Alignment.center,
                      width: 164.w,
                      height: 54.w,
                      decoration: BoxDecoration(
                          color: Styles.c_B2B1B1,
                          borderRadius: BorderRadius.circular(Styles.magin_18)),
                      child: Text(
                        "取消",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: 20.w),
                      ),
                    ).setOnClickListener(() {
                      Navigator.pop(context);
                    }),
                  ],
                ),
              ),
            ),
          );
          // );
        });
  }

  // describeExperience
  // membersTitle
  // serviceName
  onSave(bool isSave) {
    Obj.showLoading();
    Apis.getMembersInfo().then((value) {
      var jsonData = value?.data;
      _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
      // LogUtil.d("getMembersInfo success ");
      final params = {
        "memberImage":
            map?["imageUrl"] ?? (_memberInfo?.data?.memberImage ?? ""),
        "membersCorporation": map?["company"], //	聯絡人/公司名稱
        "membersEmail": map?["email"], //	会员邮箱
        "membersPhone": map?["phone"], //会员电话
        "membersName": map?["name"], //m	会员名称
        "membersNo": _memberInfo?.data?.membersNo, //m	会员
        "membersId": "${_memberInfo?.data?.membersId}", //m	会
        "version": _memberInfo?.data?.version, //m	版本號
        "membersTitle": titleControl.text,
        "describeExperience": tagControl.text,
        "serviceName": selectTypes?.join(','),
      };
      if (isSave == false) {
        Apis.editMember(params).then((value) {
          _memberInfo = MemberInfo.fromJson(value?.data);
          // print('editMember memberInfo?.code'+(_memberInfo?.code??0).toString());
          // print(value.toString());
          if (_memberInfo?.code == 201) {
            showMaxMsg("");
            return;
          }
          Obj.dismissLoading();
          ToastUtil.showToast("修改成功");
          eventBus.fire(UpdateMemberInfo());
          Get.back();
          Get.back();
          back();
        }).catchError((error) {
          // print('catchError1');
          Obj.dismissLoading();
        });
      } else {
        Apis.confirmPayment(params).then((value) {
          MemberInfo memberInfo = MemberInfo.fromJson(value?.data);
          // print('confirmPayment memberInfo?.msg'+memberInfo.msg.toString());
          // print('confirmPayment memberInfo?.code'+(memberInfo.code??0).toString());
          // print(value.toString());
          // print(value?.statusCode);
          if(memberInfo.code == 500){
            // go to top up 充值
            Get.to(const WealletPage());
            return;
          }
          if (memberInfo?.code == 201) {
            showQuoteMsg();
            return;
          }
          Obj.dismissLoading();
          ToastUtil.showToast("修改成功");
          eventBus.fire(UpdateMemberInfo());
          Get.back();
          Get.back();
          back();
        }).catchError((error) {
          // print('catchError2');
          Obj.dismissLoading();
        });
      }
    }).catchError((error) {
      // print('catchError3');
      Obj.dismissLoading();
    });
  }

  Widget info() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "基本資料",
              textAlign: TextAlign.center,
              style: getTextStyle(24.sp,
                  color: Colors.black, fontType: FontType.BOLD),
            ),
            SizedBox(
              height: 22.w,
            ),
            Text(
              "建立標題，吸引客戶",
              textAlign: TextAlign.center,
              style: getTextStyle(18.sp,
                  color: Colors.black, fontType: FontType.MID),
            ),
            const SizedBox(
              height: 12,
            ),
            MyInputWidget(
              placeholder: "",
              controller: titleControl,
            ).setContainer(margin: EdgeInsets.only(left: 0.w)),
            SizedBox(height: 34.w),
            Text(
              "服務範圍",
              textAlign: TextAlign.center,
              style: getTextStyle(24.sp,
                  color: Colors.black, fontType: FontType.BOLD),
            ),
            Text(
              "最多四個項目,添加每個服務項目需要扣除50個代幣",
              textAlign: TextAlign.center,
              style: getTextStyle(14.sp,
                  color: Colors.black),
            ),
          ],
        ),
      ),
    );
  }

  Widget serivces() {
    return SliverPadding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      sliver: SliverGrid(
        delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            return buildItem(index);
          },
          childCount: clientSearchModel?.data?.length ?? 0, //内部控件数量
        ),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 5,
          mainAxisSpacing: 10,
          childAspectRatio: 169 / 56,
        ),
      ),
    );
  }

  Widget text() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "描述你所提供的服務或經驗",
              textAlign: TextAlign.center,
              style: getTextStyle(18.sp,
                  color: Colors.black, fontType: FontType.MID),
            ),
            const SizedBox(
              height: 12,
            ),
            Container(
              // height: INPUT_ITEM_HEIGHT.w,
              height: 112.w,
              padding: EdgeInsets.symmetric(horizontal: 12.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.w),
                border: Border.all(color: MyColors.gary_158157157, width: 1.w),
              ),
              child: TextField(
                style: getTextStyle(16.sp, color: Colors.black),
                maxLines: 5,
                onChanged: (val) {
                  // widget.onTextChange!(val);
                },
                controller: tagControl,
                decoration: InputDecoration(
                  hintText: "",
                  hintStyle:
                      getTextStyle(16.sp, color: MyColors.gary_210210210),
                  border: InputBorder.none,
                ),
              ),
            ),
            Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 8.w),
              height: 60.w,
              child: Container(
                // color: Styles.mainColor,
                padding: EdgeInsets.symmetric(horizontal: 34.w, vertical: 8.w),
                decoration: BoxDecoration(
                    color: Styles.mainColor,
                    borderRadius: BorderRadius.circular(Styles.magin_16)),
                child: const Text(
                  "儲存",
                  style: TextStyle(color: Colors.white, fontSize: 18),
                ),
              ),
            ).setOnClickListener(() {
              // onSave(false);
              showQuoteMsg();
            })
          ],
        ),
      ),
    );
  }

  Widget buildItem(index) {
    if (clientSearchModel == null) {
      return Container();
    }
    String service_id =
        clientSearchModel?.data![index].serviceId.toString() ?? "";
    bool? isContain = selectTypes?.contains(service_id);
    var widget = InkWell(
      onTap: () {
        if (selectTypes?.contains(service_id) == true) {
          selectTypes?.remove(service_id);
        } else {
          // if ((selectTypes?.length ?? 0) == 5) {
          //   showMaxMsg(service_id);
          // }
          selectTypes?.add(service_id);
        }
        setState(() {});
      },
      child: Center(
        child: Text(
          clientSearchModel?.data![index].serviceName ?? "",
          overflow: TextOverflow.ellipsis,
          maxLines: 2,
          textAlign: TextAlign.center,
          style: getTextStyle(18.sp,
              fontType: FontType.MID, color: MyColors.black_0000011),
        ),
      ).setContainer(
        padding: EdgeInsets.symmetric(horizontal: 4.w),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color:
                isContain == true ? Styles.c_A8D1D0 : MyColors.gary_226226226,
            borderRadius: BorderRadius.circular(11.w)),
      ),
    );
    return widget;
  }

  @override
  Widget viewPageBody() {
    return Scaffold(
      appBar: getAppBar(title: "編輯專家檔案"),
      body: SafeArea(
        child: CustomScrollView(
          slivers: [info(), serivces(), text()],
        ),
      ),
    );
  }
}
